import reqwest from 'reqwest';
import { BASE_URL } from '../config';
const getCookie = (name)=>{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

    if(arr=document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}
const SendRequest = (action,method,data,success,error,done)=>{
    const headers = {
        'Accept': '*/*',
        "X-CSRFToken": getCookie("csrftoken")
    };
    let url = BASE_URL + action;
    reqwest({
        headers:headers,
        url: url,
        type:'json',
        method: method,
        data: data,
        success: function (resp) {
            success && success(resp);
        },
        error: function (err) {
            error && error(err);
        },
        complete:function () {
            done && done()
        }
    })
};
const UploadFile = (url,formData,success,fail)=>{
    const xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
    xhr.open("post", url, true); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            var status = xhr.status;
            if (status >= 200 && status < 300) {
                var res = JSON.parse(xhr.responseText);
                success && success(res);
            } else {
                fail && fail(status);
            }
        }
    };
    xhr.send(formData); //开始上传，发送form数据
};

module.exports = {
    SendRequest:SendRequest,
    UploadFile:UploadFile
}